package zmee.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import json.JSON;
import json.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import zmee.util.OARequestUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lijiawang
 * @Date 2022/11/17 17:39
 * @Description:同步OA人员
 */
public class OAUserTask extends AbstractTask {
    private static Log logger = LogFactory.getLog(OAUserTask.class);
    DynamicObject oauser = OARequestUtil.getInitialize().config("oauser");

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        if (oauser == null) {
            logger.info("===未配置相关配置===");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        Integer pageSize = 10000;
        JSONObject boby = new JSONObject();
        boby.put("subcompanycode", "26501");
        boby.put("sourceFrom", "text");
        boby.put("pageSize", pageSize);
        boby.put("timestamp", format);
        Integer userPageIndex = 1;
        while (true) {
            boby.put("pageIndex", userPageIndex);
            String oaUser = OARequestUtil.getOARequest(oauser, boby.toString());
            if (oaUser != null || !"".equals(oaUser)) {
                JSONObject jsonObject = JSON.parseObject(oaUser);
                logger.info("====jsonObject====:" + jsonObject);
                Boolean status = jsonObject.getBoolean("api_status");
                if (null != status && status) {
                    Integer total = jsonObject.getInteger("total");

                    String result = jsonObject.getString("result");
                    if (!StrUtil.isEmpty(result)) {
                        List<Map<String, Object>> maps = transverterMap(result, "User");
                        logger.info("===usersize===" + maps.size());
                        logger.info("===user===" + maps);
                        int i = 0;
                        for (Map userMap : maps) {
                            try {
                                logger.info("===userMap" + i + "===" + userMap);
                                addUser(userMap);
                            } catch (Exception e) {
                                logger.info("添加人员失败：" + i + e);
                            }
                            ++i;
                        }
                    }
                    if (total.equals(pageSize)) {
                        ++userPageIndex;
                    } else {
                        break;
                    }
                } else {
                    Object msg = jsonObject.get("msg");
                    throw new KDBizException("接口调用失败！原因：" + msg);
                }
            }
        }
    }

    public static List<Map<String, Object>> transverterMap(String result, String txt) {
        String[] orgs = result.split(", " + txt);
        List list = new ArrayList();
        for (int i = 0; i < orgs.length; i++) {
            String replace = orgs[i].replace("=", ":");
            if (i == 0) {
                replace = replace.replace("[" + txt, "");
            }
            if (i == orgs.length - 1) {
                replace = replace.replace("]", "");
            }
            logger.info("===添加的信息===" + replace);
            Map map = JSON.parseObject(replace, Map.class);
            if (map == null) {
                logger.info("===添加信息失败===" + replace);
            }
            list.add(map);
        }
        return list;
    }


    private void addUser(Map map) {
        String sapuserid = map.get("sapuserid").toString();
        if ("90000560".equals(sapuserid) || "165854".equals(sapuserid)) {
            return;
        }
        DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user", "id,name,number", new QFilter[]{new QFilter("number", QCP.equals, sapuserid)});
        DynamicObject dynamic;
        String loginid = map.get("loginid").toString();
        if (user != null) {
            dynamic = BusinessDataServiceHelper.loadSingle(user.getPkValue(), "bos_user");
        } else {
            dynamic = BusinessDataServiceHelper.newDynamicObject("bos_user");
        }
        boolean ispartjob_new;
        try {
            // 用强转Long来判断主/次账号
            Long.parseLong(loginid);
            // 如果是数字就把用户名就跳过不保存
            logger.error("是数字说明是次账号，则不保存直接 return; loginid = " + loginid);
            return;
        } catch (Exception e) {
            // 转Long类型失败就是用户名，然后给用户名赋值
            dynamic.set("username", loginid);
            ispartjob_new = true;
        }
        dynamic.set("name", map.get("username").toString());//姓名
        dynamic.set("oaid", map.get("id").toString());//OA人员ID
        String sex = map.get("sex").toString();
        if ("0".equals(sex)) {
            dynamic.set("gender", 2);//性别
        } else {
            dynamic.set("gender", sex);//性别
        }
        dynamic.set("number", sapuserid);//工号

        dynamic.set("enable", "1");
        dynamic.set("status", "C");
        dynamic.set("phone", map.get("mobile").toString());//电话号码
        DynamicObjectCollection entity = dynamic.getDynamicObjectCollection("entryentity");
        String zzid = map.get("zzid").toString();
        boolean ispartjob = false;
        if (existOrg(entity, zzid)) {
            if (entity.size() > 0) {
                ispartjob = true;
            }
            DynamicObject entitynew = entity.addNew();
            DynamicObject org = BusinessDataServiceHelper.loadSingle("bos_org", "id,name,number", new QFilter[]{new QFilter("number", QCP.equals, zzid)});
            entitynew.set("dpt", org);
            entitynew.set("position", map.get("gwname").toString());
            // 是否兼职
            entitynew.set("ispartjob", ispartjob_new);
        }
        OperationResult userOperationResult = SaveServiceHelper.saveOperate("bos_user", new DynamicObject[]{dynamic}, OperateOption.create());
        logger.info("===userOperationResult===" + userOperationResult);
    }

    private Boolean existOrg(DynamicObjectCollection dynamicObjects, String zzid) {
        if (dynamicObjects.size() == 0) {
            return true;
        }
        for (DynamicObject dynamic : dynamicObjects) {
            String string = dynamic.getString("dpt.number");
            if (string.equals(zzid)) {
                return false;
            }
        }
        return true;
    }
}
